#!/usr/bin/env sage -python

from sage.all import *
import random
import time as t
#import antigravity

start = t.time()

gen_size=96

L1_size=32
L2_size=64
L3_size=0

#field = GF(2**8, name='a')
field = GF(2, name='a')
nb_sim = 10000
nb_trans = 185

layer_3_active = false

Pr_liste = [[50,50,0],[30,70,0],[40,60,0]]



gammas = 3


for a in range(0,gammas):

	L1_full_rank_counter=vector(ZZ,nb_trans)
	L2_full_rank_counter=vector(ZZ,nb_trans)
	L3_full_rank_counter=vector(ZZ,nb_trans)
	
	Pr = Pr_liste[a]
	for x in range(0,nb_sim):
	
		print x
		
		#Generate the matrices
		M1=matrix(field,nb_trans,L1_size)
		M2=matrix(field,nb_trans,L2_size)
		M3=matrix(field,nb_trans,L3_size)
	
		layer_1_index=0
		layer_2_index=0
		layer_3_index=0	
		
		new_boolean_1=false
		new_boolean_2=false
		new_boolean_3=false
		
		random_check = vector(ZZ,nb_trans)
		
		for n in range(0,nb_trans):
				
			r=math.ceil(random.uniform(0,100))
			
			if r<=Pr[0]:
				M1[layer_1_index,:]=random_vector(field,L1_size)
				layer_1_index+=1
				
			elif r<=(Pr[0]+Pr[1]):
				M2[layer_2_index,:]=random_vector(field,L2_size)
				layer_2_index+=1
			else:
				M3[layer_3_index,:]=random_vector(field,L3_size)
				layer_3_index+=1
		
			
			if n>=L1_size and new_boolean_1==false:
				if M1.rank()==L1_size:
					new_boolean_1=true
					for i in range(n,nb_trans):
						L1_full_rank_counter[i]+=1
				
			if n>=L2_size and new_boolean_2==false and new_boolean_1==true:
				if M2.rank()==L2_size:
					new_boolean_2=true
					for i in range(n,nb_trans):
						L2_full_rank_counter[i]+=1
				
			if n>=L3_size and new_boolean_3==false:
				if M3.rank()==L3_size:
					new_boolean_3=true
					for i in range(n,nb_trans):
						L3_full_rank_counter[i]+=1
			
			if new_boolean_1 and new_boolean_2 and new_boolean_3 and layer_3_active:
				break
			elif new_boolean_1 and new_boolean_2:
				break
		
		
		
		
	#Save layer 1 datas
	path = 'data_points_L1_NEW_g1%d' % Pr[0] + '.txt'
	L1_file = open(path,'w')
	L1_file.write(str(L1_full_rank_counter).strip('()'))
	L1_file.close()
	#Save layer 2 data
	path = 'data_points_L2_NEW_g1%d' % Pr[0] + '.txt'
	L2_file = open(path,'w')
	L2_file.write(str(L2_full_rank_counter).strip('()'))
	L2_file.close()
	
	plot = list_plot(L1_full_rank_counter/nb_sim, plotjoined=True, legend_label='Layer 1',gridlines=True)
	plot += list_plot(L2_full_rank_counter/nb_sim, plotjoined=True,color='green', legend_label='Layer 2')
	plot += list_plot(L3_full_rank_counter/nb_sim, plotjoined=True,color='purple', legend_label='Layer 3')
	plot.save('NEW_plot.eps')

	plot.show()
		
		
		


print "This script took ", (t.time()-start)/60, " minutes."